<template>
  <div class="building">
    <div class="building_top">
      <div class="building_top_text">建筑</div>
      <el-switch
        v-model="switchValue"
        active-color="#409EFF"
        inactive-color="#d1d1d1"
        @change="switchChange"
        :disabled="isdisabled"
      >
      </el-switch>
    </div>
    <div class="building_middle">
      <!-- <div class="building_middle_title">影响建筑面积统计</div> -->
      <div class="building_middle_button">
        <div
          class="building_middle_button_image"
          :class="boxBlockItem == 0 ? 'image_active' : ''"
        >
          <div
            class="building_middle_content"
            @click="box_blockClick(0)"
            :style="{
              background:
                boxBlockItem == 0
                  ? 'linear-gradient(180deg, rgba(255, 255, 255, 5e-05) 0%, rgba(33, 136, 205, 0.5) 99.13%), linear-gradient(180deg, #1F3E72 0%, #112650 100%)'
                  : 'linear-gradient(180deg, #1f3e72 0%, #112650 100%)',
            }"
          >
            <div class="building_middle_content_top">选址涉及建筑(栋)</div>
            <div class="building_middle_content_bottom">
              {{ areaDatas1 ? areaDatas1 : "暂无数据" }}
              {{ areaDatas1 ? "栋" : "" }}
            </div>
          </div>
        </div>

        <div
          class="building_middle_button_image"
          :class="boxBlockItem == 1 ? 'image_active' : ''"
        >
          <div
            class="building_middle_content"
            @click="box_blockClick(1)"
            :style="{
              background:
                boxBlockItem == 1
                  ? 'linear-gradient(180deg, rgba(255, 255, 255, 5e-05) 0%, rgba(33, 136, 205, 0.5) 99.13%), linear-gradient(180deg, #1F3E72 0%, #112650 100%)'
                  : 'linear-gradient(180deg, #1f3e72 0%, #112650 100%)',
            }"
          >
            <div class="building_middle_content_top">合计建筑面积</div>
            <div class="building_middle_content_bottom">
              {{ areaDatas2 ? areaDatas2 : "暂无数据" }}
              <span v-if="areaDatas2">{{ unit | filterUnit() }}</span>
            </div>
          </div>
        </div>

        <div
          class="building_middle_button_image"
          :class="boxBlockItem == 2 ? 'image_active' : ''"
        >
          <div
            class="building_middle_content"
            @click="box_blockClick(2)"
            :style="{
              background:
                boxBlockItem == 2
                  ? 'linear-gradient(180deg, rgba(255, 255, 255, 5e-05) 0%, rgba(33, 136, 205, 0.5) 99.13%), linear-gradient(180deg, #1F3E72 0%, #112650 100%)'
                  : 'linear-gradient(180deg, #1f3e72 0%, #112650 100%)',
            }"
          >
            <div class="building_middle_content_top">建筑占地面积</div>
            <div class="building_middle_content_bottom">
              {{ areaDatas3 ? areaDatas3 : "暂无数据" }}
              <span v-if="areaDatas3">{{ unit | filterUnit() }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState } from "vuex";
import { getXzRegion } from "../../../../../api/connect.js";
import tableNames from "../../left/tableNames.json";

export default {
	data() {
		return {
			boxBlockItem: 0,

			// 换算单位
			units: "",

			// 获取到选址涉及建筑的值
			areaDatas1: "",

			// 获取到合计建筑面积的值
			areaDatas2: "",

			// 获取到建筑占地面积的值
			areaDatas3: "",

			//switch的值
			switchValue: false,
			isdisabled: false, //是否禁用

			// 建筑图层的loading
			jzLoading: false,
		};
	},
	computed: {
		...mapState("Sjsx", ["jzData", "unit", "isRegion"]),
	},
	mounted() {
		this.changeUnit();
		// this.changePie();
	},
	methods: {
		...mapActions({
			setJzloading_act: "Sjsx/setJzloading_act",
		}),
		// 判断选中了哪个盒子
		box_blockClick(val) {
			this.boxBlockItem = val;
		},

		// 改变单位，改变值
		changeUnit() {
			// console.log(this.AreaData,"AreaData的值");
			// console.log(this.unit,"unit的值");
			if (this.unit == "m²") {
				//如果单位是平方米
				this.areaDatas1 = this.jzData.buildNum.value; // 选址涉及建筑
				this.areaDatas2 = this.jzData.area.value; // 合计建筑面积
				this.areaDatas3 = this.jzData.buildArea.value; // 建筑占地面积
				this.units = "平方米"; //改变单位
			} else if (this.unit == "ha") {
				// 如果单位是公顷
				// this.areaDatas = this.jzData.ha;
				this.areaDatas1 = this.jzData.buildNum.value; // 选址涉及建筑
				this.areaDatas2 = this.jzData.areaHa.value; // 合计建筑面积
				this.areaDatas3 = this.jzData.buildAreaHa.value; // 建筑占地面积
				this.units = "公顷";
			} else if (this.unit == "mu") {
				// 如果单位是亩
				// this.areaDatas = this.jzData.mu;
				this.areaDatas1 = this.jzData.buildNum.value; // 选址涉及建筑
				this.areaDatas2 = this.jzData.areaMu.value; // 合计建筑面积
				this.areaDatas3 = this.jzData.buildAreaMu.value; // 建筑占地面积
				this.units = "亩";
			}
		},

		// 点击后画面
		async getRegionData() {
			try {
				const temp = tableNames.find(
					(r) => r.layer_chinese_name === "2019建筑物普查"
				);
				// find 返回的是第一个满足要求的 值
				// filter 返回的是所有满足要求的 数组
				// const temp = tableNames.filter( r => r.layer_chinese_name === "2019建筑物普查")
				console.log(temp, "获取到2019建筑物普查的值");
				if (this.switchValue == true) {
					const result = await getXzRegion(this.isRegion, temp);
					console.log(result, "建筑的result");
					const polygon3ddata = [];
					// const polygondata = [];
					const polylinedata = [];

					result.data.map((item, index) => {
						let itemJson = JSON.parse(item);
						const r = parseInt(temp.hex.substr(1, 2), 16) / 255;
						const g = parseInt(temp.hex.substr(3, 2), 16) / 255;
						const b = parseInt(temp.hex.substr(5, 2), 16) / 255;
						const colorArray = [r, g, b, 0.3];
						// let o = {
						//   id: "polygon_" + temp.layer_english_name + "_" + index,
						//   coordinates: itemJson.geometry.coordinates,
						//   // color: [
						//   //   0.2784313725490196,
						//   //   0.8117647058823529,
						//   //   0.0745098039215686,
						//   //   0.7,
						//   // ], //多边形的填充颜色
						//   color: colorArray, //多边形的填充颜色

						//   frameColor: [1, 1, 0, 0.8], //边框颜色
						//   frameThickness: 2, //边框厚度
						//   intensity: 1, //亮度
						//   // style: window.PolygonStyle.SingleColor, //单色 请参照API开发文档选取枚举
						//   style: 0,
						//   depthTest: false, //是否做深度检测
						//   //   coordinateType: 1,
						// };

						// 让建筑有高度
						let o = {
							id: "polygon3d_" + temp.layer_english_name + "_" + index,
							coordinates: itemJson.geometry.coordinates,
							// color: [1, 1, 1, 0.6], //颜色值
							// color: [0.188, 0.733, 0.623, 0.8],
							color: colorArray, //多边形的填充颜色

							// height: 100, //3D多边形的高度
							height: itemJson.properties.bldg_heigh, //3D多边形的高度
							intensity: 2.0, //亮度
							style: 10,
						};

						// if (this.XzTreeDataPolyon.indexOf(o.id) < 0) {
						//   this.XzTreeDataPolyon.push(o.id);
						// }

						// polygondata.push(o);
						polygon3ddata.push(o);
						itemJson.geometry.coordinates.forEach((item) => {
							// console.log(item, "item");
							if (
								item instanceof Array &&
								item[0] instanceof Array &&
								item[0][0] instanceof Array
							) {
								item.forEach((mon) => {
									polylinedata.push({
										id: "polyline_" + temp.layer_english_name + "_" + index,
										coordinates: mon, //构成折线的坐标点数组
										color: [1, 1, 1, 1], //折线颜色
										style: 0, //折线样式 参考样式枚举：PolylineStyle
										// style: 5, //贴地
										thickness: 2, //折线宽度
										intensity: 1, //亮度
										flowRate: 0.5, //流速
										tiling: 0, //材质贴图平铺比例
										shape: 0, //折线类型 0：直线， 1：曲线
										depthTest: false, //是否做深度检测
										coordinateType: 0,
									});
								});
							} else {
								polylinedata.push({
									id: "polyline_" + temp.layer_english_name + "_" + index,
									coordinates: item, //构成折线的坐标点数组
									color: [1, 1, 1, 1], //折线颜色
									style: 0, //折线样式 参考样式枚举：PolylineStyle
									// style: 5, // 贴地
									thickness: 2, //折线宽度
									intensity: 1, //亮度
									flowRate: 0.5, //流速
									tiling: 0, //材质贴图平铺比例
									shape: 0, //折线类型 0：直线， 1：曲线
									depthTest: false, //是否做深度检测
									coordinateType: 0,
								});
							}
						});
					});

					// temp["polygondata"] = polygondata;
					temp["polygon3ddata"] = polygon3ddata;
					temp["polylinedata"] = polylinedata;
					// await window.__g.polyline.add(polylinedata);  // 添加线的

					// await window.__g.polygon.add(polygondata);
					// await window.__g.polygon.focus(polygondata.map((r) => r.id));

					// await window.__g.polygon3d.add(polygon3ddata);
					// await window.__g.polygon3d.focus(polygon3ddata.map((r) => r.id));

					// 一次性只能画3000个3d面或线
					const fn1 = async function (list, type) {
						let skip = 3000;
						for (let i = 0; i < list.length; ) {
							const limit = i + skip;
							if (limit > list.length) {
								limit = list.length;
							}
							const tmp = list.slice(i, limit);
							type == 1
								? await window.__g.polyline.add(tmp)
								: await window.__g.polygon3d.add(tmp);
							// await window.__g.polyline.add(tmp);
							// await window.__g.polygon.add(tmp);
							i += skip;
						}
					};

					// await fn1(polylinedata, 1);
					await fn1(polygon3ddata, 2);
					this.jzLoading = false;
					// this.$store.dispatch("Sjsx/setJzloading_act", this.jzLoading);
					this.setJzloading_act(this.jzLoading);
				} else if (this.switchValue == false) {
					// if (temp["polygondata"] && temp["polygondata"] instanceof Array) {
					if (temp["polygon3ddata"] && temp["polygon3ddata"] instanceof Array) {
						// let polygondataIds = [];
						let polygon3ddataIds = [];
						let polylineIds = [];

						// temp["polygondata"].forEach((element) => {
						//   polygondataIds.push(element.id);
						// });
						temp["polygon3ddata"].forEach((element) => {
							polygon3ddataIds.push(element.id);
						});
						temp["polylinedata"].forEach((element) => {
							polylineIds.push(element.id);
						});
						// await window.__g.polygon.delete(polygondataIds);
						await window.__g.polygon3d.delete(polygon3ddataIds);
						await window.__g.polyline.delete(polylineIds);

						// window.__g.polygon.updateEnd();
						console.log("已经删除");
					}
				}
			} catch (error) {
				console.log(error);
				this.$message.error("服务器请求异常，图层加载失败！");
				this.switchValue = false; // 请求失败后，将switch框设置为false
				this.jzLoading = false;
				// this.$store.dispatch("Sjsx/setJzloading_act", this.jzLoading);
				this.setJzloading_act(this.jzLoading); // 请求失败后，将loading窗关闭
			}
		},

		// switch的改变
		async switchChange(val) {
			console.log(val, "switch改变");
			this.isdisabled = true;
			if (val) {
				if (this.areaDatas1 || this.areaDatas2 || this.areaDatas3) {
					this.jzLoading = true;
					this.setJzloading_act(this.jzLoading);
					await this.getRegionData();
					this.jzLoading = false;
					this.setJzloading_act(this.jzLoading);
				} else {
					this.$message.warning("选址不涉及，暂无图层");
					setTimeout(() => {
						this.switchValue = false;
					}, 300);
				}
			} else {
				await this.getRegionData();
			}
			this.isdisabled = false;
		},
	},
	filters: {
		filterUnit(val) {
			if (val == "ha") {
				return "公顷";
			} else if (val == "mu") {
				return "亩";
			} else if (val == "m²") {
				return "平方米";
			}
		},
	},
	// watch:{
	//   AreaData:{
	//     handler(newval){
	//       console.log(newval,"面积的值");

	//     }
	//   }
	// }
};
</script>

<style lang="scss" scoped>
.building {
	margin-top: 25px;
	.building_top {
		display: flex;
		align-items: center;
		background: url("../../../../../assets/images/home/top.png");
		width: 440px;
		background-size: cover;
		.building_top_text {
			padding-left: 16px;
			font-family: OPPOSans;
			font-style: normal;
			font-weight: normal;
			font-size: 20px;
			line-height: 24px;
			color: #ffffff;
			margin-right: 120px;
		}
	}
	.building_middle {
		display: flex;
		flex-direction: column;
		padding-left: 15px;
		margin-top: 10px;
		.building_middle_title {
		}
		.building_middle_button {
			margin-top: 10px;
			display: flex;
			justify-content: center;
			width: 390px;
			flex-wrap: wrap;
			.image_active {
				background: url("../../../../../assets/images/home/jianzhuBox.png");
				background-size: 100% 100%;
			}
			.building_middle_button_image {
				width: 254px;
				height: 85px;
				margin-bottom: 15px;
				.building_middle_content {
					width: 254px;
					height: 85px;
					background: linear-gradient(180deg, #1f3e72 0%, #112650 100%);
					display: flex;
					flex-direction: column;
					justify-content: center;
					border-radius: 4px;
					cursor: pointer;
					margin-bottom: 15px;
					.building_middle_content_top {
						font-family: OPPOSans;
						font-style: normal;
						font-weight: normal;
						font-size: 18px;
						line-height: 21px;
						color: rgba(255, 255, 255, 0.85);
						padding-left: 20px;
					}
					.building_middle_content_bottom {
						padding-top: 5px;
						font-family: HuXiaoBo-NanShen;
						font-style: normal;
						font-weight: normal;
						font-size: 20px;
						line-height: 19px;
						color: #83fae5;
						padding-left: 20px;
					}
				}
			}
		}
	}
}
</style>
